import logging
import os
from aliyun.log import LogClient, PutLogsRequest, LogItem
# from common.tools.public import change_timestamp_to_str
from datetime import datetime
from config.base import settings

class Log:
    def __init__(self,name:str):
        self.name = name
    def get_logger(self) -> logging:
        # 创建一个日志器
        logger = logging.getLogger(self.name)
        # 确保日志不会传播到父日志器
        logger.propagate = False
        # 避免重复添加处理器
        if not logger.handlers:
            logger.setLevel(logging.INFO)

        # 创建阿里云日志服务处理器
        # 配置 SLS 相关参数

        sls_handler = SLSLogHandler(
            endpoint=settings.ALIYUN_SLS_ENDPOINT,
            access_key_id=settings.ALIYUN_ACCESS_KEY_ID,
            access_key_secret=settings.ALIYUN_ACCESS_KEY_SECRET.get_secret_value(),
            project=settings.ALIYUN_PROJECT,
            logstore=settings.ALIYUN_LOGSTORE,
        )
        
        # 创建控制台处理器
        handler = logging.StreamHandler()
        logger.setLevel(logging.INFO)
        handler.setLevel(logging.INFO)  # 设置日志级别
        if settings.LOG_LEVEL == "DEBUG":
            logger.setLevel(logging.DEBUG)
            handler.setLevel(logging.DEBUG)  # 设置日志级别
    
        # 创建日志格式
        formatter = logging.Formatter('%(levelname)s: \t %(asctime)s - %(name)s - %(message)s')

        # 设置日志格式
        handler.setFormatter(formatter)

        # 将处理器添加到日志器
        logger.addHandler(handler)
        
        # logger.addHandler(sls_handler)

        # 返回日志器
        return logger 
    
class SLSLogHandler(logging.Handler):

    log_group_id_counter = 0
    context_prefix = "5FA51423DDB54FDB"
    # context_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k=16))

    def __init__(self, endpoint, access_key_id, access_key_secret, project, logstore):
        super().__init__()
        self.client = LogClient(endpoint, access_key_id, access_key_secret)
        self.project = project
        self.logstore = logstore
        self.topic = "python_sdk"
        self.source = "python_sdk"



    @classmethod
    def generate_pack_id(cls):
        """生成符合要求的PackId"""
        # 生成递增的日志组ID，并格式化为大写的十六进制
        log_group_id_hex = f"{cls.log_group_id_counter:X}"
        # 增加计数器
        cls.log_group_id_counter += 1
        return f"{cls.context_prefix}-{log_group_id_hex}"

    def emit(self, record):
        try:
            # 格式化日志消息
            # 将时间戳转换为 datetime 对象
            datetime_obj = datetime.fromtimestamp(record.created)
            # 格式化输出时间
            formatted_time = datetime_obj.strftime("%Y-%m-%d %H:%M:%S.%f")

            log_message = self.format(record)
            log_item = LogItem(contents=[
                ("ENV", os.getenv("env")),
                ("level", record.levelname),
                ("model_name", record.name),
                ("message", log_message),
                ("time", formatted_time),
            ])
            request = PutLogsRequest(self.project, self.logstore, "", "", [log_item])
            request.set_log_tags([('__pack_id__', self.generate_pack_id())])
            self.client.put_logs(request)
        except Exception as e:
            print(f"Failed to send log to SLS: {e}")